package com.manage.func.activity.controller;

import java.io.File;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.manage.base.bean.CommonResultBean;
import com.manage.base.controller.BaseController;
import com.manage.config.model.Config;
import com.manage.config.service.IConfigService;
import com.manage.func.activity.model.ActivityBean;
import com.manage.func.activity.model.ActivityVsUserBean;
import com.manage.func.activity.service.IActivityService;
import com.manage.user.model.User;
import com.manage.util.KeyValueHelper;
import com.manage.util.StringUtil;
import com.manage.util.SystemUtil;
/**
 * 新闻管理
 * @author ouyangyf
 *
 */
@Controller
@RequestMapping("/activity")
public class ActivityController extends BaseController {

	private static final long serialVersionUID = 1L;

	static final Logger LOG = LoggerFactory.getLogger(ActivityController.class);

	@Autowired
	private IActivityService activityService;
	
	@Autowired
	private IConfigService iConfigService;

	// 查询新闻
	@RequestMapping(value = "select", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean select(@RequestParam("data") String data) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("activity select called: " + data);
			ActivityBean bean = fromJson(data, ActivityBean.class);
			bean = convertSearchTime(bean);
			if (bean != null) {
				List<ActivityBean> beans = activityService.selectActivityList(bean);
				beans = convertHttp(beans);
				int size = activityService.selectTotalCount(bean);
				sys.put("activitys", beans);
				sys.put("size", size);
				return sys;
			}
			sys.setErrorMsg("请求参数为空");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}
	
	/**
	 * 转换URL
	 * @param activityBeans
	 * /images/activity/1463026911636859951.jpg
	 */
	protected List<ActivityBean> convertHttp(List<ActivityBean> activityBeans) {
		String context = SystemUtil.getAppProp("image_context");
		for (ActivityBean bean : activityBeans) {
			if (StringUtil.notEmpty(bean.previewPicture)) {
				bean.previewPicture="http://" + context +  bean.previewPicture;
			}
			if (StringUtil.notEmpty(bean.contentPicture)) {
				bean.contentPicture="http://" + context +  bean.contentPicture;
			}
			if (StringUtil.notEmpty(bean.homePageImage)) {
				bean.homePageImage="http://" + context +  bean.homePageImage;
			}
		}
		return activityBeans;
	}

	private ActivityBean convertSearchTime(ActivityBean param) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			if (StringUtil.notEmpty(param.createTimeStringStart)) {
				param.createTimeStart = new Timestamp(sdf.parse(param.createTimeStringStart).getTime());
			} else {
				param.createTimeStringStart = null;
			}

			if (StringUtil.notEmpty(param.createTimeStringEnd)) {
				param.createTimeEnd = new Timestamp(sdf.parse(param.createTimeStringEnd).getTime());
			} else {
				param.createTimeStringEnd = null;
			}

			if (StringUtil.notEmpty(param.updateTimeStringStart)) {
				param.updateTimeStart = new Timestamp(sdf.parse(param.updateTimeStringStart).getTime());
			} else {
				param.updateTimeStringStart = null;
			}

			if (StringUtil.notEmpty(param.updateTimeStringEnd)) {
				param.updateTimeEnd = new Timestamp(sdf.parse(param.updateTimeStringEnd).getTime());
			} else {
				param.updateTimeStringEnd = null;
			}

			if (StringUtil.notEmpty(param.startTimeStringStart)) {
				param.startTimeStart = new Timestamp(sdf.parse(param.startTimeStringStart).getTime());
			} else {
				param.startTimeStringStart = null;
			}

			if (StringUtil.notEmpty(param.startTimeStringEnd)) {
				param.startTimeEnd = new Timestamp(sdf.parse(param.startTimeStringEnd).getTime());
			} else {
				param.startTimeStringEnd = null;
			}
			
			if (StringUtil.notEmpty(param.endTimeStringStart)) {
				param.endTimeStart = new Timestamp(sdf.parse(param.endTimeStringStart).getTime());
			} else {
				param.endTimeStringStart = null;
			}

			if (StringUtil.notEmpty(param.endTimeStringEnd)) {
				param.endTimeEnd = new Timestamp(sdf.parse(param.endTimeStringEnd).getTime());
			} else {
				param.endTimeStringEnd = null;
			}

		} catch (ParseException e) {
			LOG.error(e.getMessage(), e);
		}
		return param;
	}
	
	// 添加活动
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean add(@RequestParam("data") String data,HttpServletRequest request) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("activity add called: " + data);
			User sysuser = (User) request.getSession().getAttribute(Config.USER_SESSION);
			if(null==sysuser){
				sys.setErrorMsg("请先登录再进行操作");
				return sys;
			}
			ActivityBean bean = fromJson(data, ActivityBean.class);
			
			if(!checkHomePageTotalCountAdd(bean)){
				sys.setErrorMsg("轮播图片数量已经达到上限，不能再进行添加");
				return sys;
			}
			bean.adminId=sysuser.getUserId();
			bean=convertImagePath(bean);
			if (bean != null) {
				activityService.insertActivity(bean);
				sys.setResult_code(Config.SUCCESS);
				sys.setResult_message(Config.SUCCESS_MSG);
				return sys;
			}
			sys.setErrorMsg("请求参数为空");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}
	
	private boolean checkHomePageTotalCountAdd(ActivityBean bean){
		KeyValueHelper.load(iConfigService.selectKeyValueList());
		String db_count=KeyValueHelper.get("homepage_total_count");
		int config_count=5;
		if(null!=db_count||!"".equals(db_count)){
			config_count=Integer.valueOf(db_count);
		}
		int current_count=iConfigService.selectHomePageTotalCount();
		if(bean.getIsHomePage()==0){
			return true;
		}
		if(current_count<config_count&&bean.getIsHomePage()==1){
			return true;
		}
		return false;
	}
	
	private ActivityBean convertImagePath(ActivityBean param) {
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			if (StringUtil.notEmpty(param.previewPicture)) {
				String str=param.previewPicture.split(Config.ACTIVITY_IMAGE_HTTP)[1];
				param.previewPicture=Config.ACTIVITY_IMAGE_HTTP+str;
			}
			
			if (StringUtil.notEmpty(param.homePageImage)) {
				String str=param.homePageImage.split(Config.ACTIVITY_IMAGE_HTTP)[1];
				param.homePageImage=Config.ACTIVITY_IMAGE_HTTP+str;
			}
			
			if (StringUtil.notEmpty(param.contentPicture)) {
				String str=param.contentPicture.split(Config.ACTIVITY_IMAGE_HTTP)[1];
				param.contentPicture=Config.ACTIVITY_IMAGE_HTTP+str;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return param;
	}
	
	/**
	 * 图片上传
	 * 
	 * @param uploadFile
	 * @param data
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/image/upload")
	@ResponseBody
	public CommonResultBean pictureUpload(
			@RequestParam(value = "uploadFile", required = false) MultipartFile uploadFile,HttpServletRequest request) {
		if (uploadFile == null || uploadFile.getOriginalFilename().trim().equals("")) {
			CommonResultBean commonResultBean = new CommonResultBean();
			commonResultBean.setResult_code(Config.FAILE);
			commonResultBean.setResult_message("图片为空，上传失败");
			return commonResultBean;
		} else {
			try {
				String rootPath = super.getWebRootPath(request);
				String rootUrl = super.getWebRootUrl(request);
				String fileFullName = saveImage(uploadFile,rootPath, rootUrl);
				CommonResultBean commonResultBean = new CommonResultBean();
				commonResultBean.setResult_code(Config.SUCCESS);
				commonResultBean.setResult_message("主图片上传成功");
				Map<String, Object> result_map = new HashMap<String, Object>();
				result_map.put("url", fileFullName);
				commonResultBean.setResult_map(result_map);
				return commonResultBean;

			} catch (Exception e) {
				e.printStackTrace();
				CommonResultBean commonResultBean = new CommonResultBean();
				commonResultBean.setResult_code(Config.FAILE);
				commonResultBean.setResult_message("主图片上传异常");
				return commonResultBean;
			}

		}
	}
	
	private String saveImage(MultipartFile uploadFile,String rootPath, String rootUrl) {
		try {
			//未完成，调试再弄
			String httpUrl = Config.HTTP_TITLE+SystemUtil.getAppProp("image_context");
			String suffix = uploadFile.getOriginalFilename().substring(uploadFile.getOriginalFilename().lastIndexOf("."));
			String prePath = rootPath+ Config.ACTIVITY_IMAGE_PATH ;
			String filePath =System.currentTimeMillis() +getFixLenthString(6)+ suffix;
			String returnPath = httpUrl +Config.ACTIVITY_IMAGE_HTTP +filePath;
			String savePath = prePath + filePath;
			File preDir = new File(prePath);
			if (!preDir.exists()) {
				preDir.mkdirs();
			}
			uploadFile.transferTo(new File(savePath));
			return returnPath;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	private static String getFixLenthString(int strLength) {  
	      
	    Random rm = new Random();  
	    // 获得随机数  
	    double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);  
	    // 将获得的获得随机数转化为字符串  
	    String fixLenthString = String.valueOf(pross);  
	    // 返回固定的长度的随机数  
	    return fixLenthString.substring(1, strLength + 1);  
	}  
	
	// 更新活动
	// 添加活动
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean update(@RequestParam("data") String data,HttpServletRequest request) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("activity update called: " + data);
			User sysuser = (User) request.getSession().getAttribute(Config.USER_SESSION);
			if(null==sysuser){
				sys.setErrorMsg("请先登录再进行操作");
				return sys;
			}
			ActivityBean bean = fromJson(data, ActivityBean.class);
			
			if(!checkHomePageTotalCountUpdate(bean)){
				sys.setErrorMsg("轮播图片数量已经达到上限，不能再进行添加");
				return sys;
			}
			
			bean.adminId=sysuser.getUserId();
			bean=convertImagePath(bean);
			if (bean != null) {
				activityService.updateActivity(bean);
				sys.setResult_code(Config.SUCCESS);
				sys.setResult_message(Config.SUCCESS_MSG);
				return sys;
			}
			sys.setErrorMsg("请求参数为空");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}
	
	private boolean checkHomePageTotalCountUpdate(ActivityBean bean){
		KeyValueHelper.load(iConfigService.selectKeyValueList());
		int current_count=iConfigService.selectHomePageTotalCount();
		
		int oldHomePageFlag=activityService.selectActivityById(bean).getIsHomePage();
		String db_count=KeyValueHelper.get("homepage_total_count");
		int config_count=5;
		if(null!=db_count||!"".equals(db_count)){
			config_count=Integer.valueOf(db_count);
		}
		
		if(bean.getIsHomePage()==0){
			return true;
		}
		
		if(oldHomePageFlag==1){
			return true;
		}
		else{
			if(current_count<config_count&&bean.getIsHomePage()==1){
				return true;
			}
			return false;
		}
	}
	
	// 删除新闻
		@RequestMapping(value = "delete", method = RequestMethod.POST)
		@ResponseBody
		public CommonResultBean delete(@RequestParam("data") String data) {
			LOG.info("Activity delete: " + data);
			CommonResultBean sys = new CommonResultBean();
			try {
				ActivityBean bean = fromJson(data, ActivityBean.class);
				// int i = 
				activityService.deleteActivity(bean);
				sys.setResult_code(Config.SUCCESS);
				sys.setResult_message(Config.SUCCESS_MSG);
				return sys;
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
				sys.setError();
			}
			return sys;
		}
		
		
		/**
		 * 查询参加活动用户
		 * @param data
		 * @return
		 */
		@RequestMapping(value = "/user/select", method = RequestMethod.POST)
		@ResponseBody
		public CommonResultBean userSelect(@RequestParam("data") String data) {
			CommonResultBean sys = new CommonResultBean();
			try {
				LOG.info("activity select called: " + data);
				ActivityBean bean = fromJson(data, ActivityBean.class);
				if (bean != null) {
					List<ActivityVsUserBean> beans = activityService.selectActivityUserList(bean);
					int size = activityService.selectActivityUserCount(bean);
					sys.put("users", beans);
					sys.put("size", size);
					return sys;
				}
				sys.setErrorMsg("请求参数为空");
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
				sys.setError();
			}
			return sys;
		}
	
}
